package top.so.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/fileupload")
public class FileLoadController {

    @RequestMapping("")
    public ModelAndView index(){
        return new ModelAndView("main/uploadFile");
    }
    @RequestMapping(value = "upload")
    public ModelAndView uploadFile( @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        System.out.println("开始");
        String path ="D:\\code\\javacode\\newBlog\\picture\\";
        String fileName = file.getOriginalFilename();

        System.out.println(path+fileName);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView mav = new ModelAndView("main/successFile");

        mav.addObject("fileUrl",path+fileName);
        return mav;
    }
}
